<template>
  <div>
    <!-- 定价规则表单 -->
    <el-form
      :model="priceRuleForm"  
      :rules="priceRuleForm.clear_mode!=3?priceRuleFormRules:nosettle_priceRuleFormRules"
      ref="priceRuleFormRef"
      label-width="130px"
    >
      <el-form-item label="所属礼包" prop="gift"> 
        <el-input
          disabled
          placeholder="请输入所属礼包"
          v-model="priceRuleForm.gift_name" 
          style="width:50%" 
        > 
        </el-input>
      </el-form-item>
      <el-form-item label="所属采购实体" prop="service_id"> 
         <el-select
            disabled
            placeholder="请输入所属采购实体"
            v-model="priceRuleForm.service_id"
            style="width:50%"  
            filterable
            clearable 
          >
             <el-option
                v-for="item in selectData.get_service"
                :key="item.id"
                :label="item.name"
                :value="item.id" 
              >
              </el-option> 
          </el-select> 
      </el-form-item>
      <el-form-item label="结算类型" prop="clear_mode"> 
       
           <el-select   
            :disabled="hasClearmode?true:false"
            v-model="priceRuleForm.clear_mode"
            placeholder="请选择结算类型"
            filterable
            clearable
            style="width:50%"
            value-key="id"
          >
             <el-option
                v-for="item in selectData.clear_mode"
                :key="item.id"
                :label="item.name" 
                :value="typeof priceRuleForm.clear_mode=='string' ? item.id+'' :item.id"
              > <!-- :value="item" -->
              </el-option> 
          </el-select> 
      </el-form-item>
      
      <el-form-item v-show="priceRuleForm.clear_mode!=3?true:false" label="计价类型" :required="priceRuleForm.clear_mode!=3?true:false" prop="valuation_type">
          <el-select
            v-model="priceRuleForm.valuation_type"
            placeholder="请选择"
            filterable
            clearable
            style="width:50%"
          >
            <el-option
                v-for="item in selectData.valuation_type"
                :key="item.id"
                :label="item.name" 
                :value="item.id"
              ><!-- :value="item.id"  :value="typeof priceRuleForm.valuation_type=='string' ? item.id+'' :item.id"-->
            </el-option> 
          </el-select>
      </el-form-item> 
      <el-form-item label="统一价" prop="price" required>
        <el-input 
          :disabled="priceRuleForm.clear_mode==3?true:false"
          style="width:50%"
          placeholder="请输入统一价"
          v-model="priceRuleForm.price" 
        ><!--   oninput="value=value.replace(/[^\d.]/g,'')" -->
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="定价规则有效期" required style="width: 59%">
        <el-col :span="11">
          <el-form-item prop="start_time">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              v-model="priceRuleForm.start_time"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1">-</el-col>
        <el-col :span="11">
          <el-form-item prop="end_time">
            <el-date-picker
              v-model="priceRuleForm.end_time"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期" 
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="priceRuleForm.remark"
          type="textarea" 
          show-word-limit
          maxlength="500"
          style="width:50%"
        ></el-input>
      </el-form-item>
      <el-form-item label="设置差异价" prop="is_diff">
        <el-switch v-model="priceRuleForm.is_diff"></el-switch>
      </el-form-item>
    </el-form>

    <div v-show="priceRuleForm.is_diff==true"><!---->
      <!-- 差异价规则表 --> 
      <el-table 
        :data="diffTableData"
        border
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="编号"> </el-table-column>
        
        <el-table-column prop="code" label="机构名称【ID】" width="200px">
           <template slot-scope="scope"> 
            <div
              v-if="scope.row.editRowVisible"
            ><!-- v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id"-->
              <el-cascader
                :options="selectData.org_tree"
                :props="orgprops"
                clearable
                filterable
                :show-all-levels="false"
                v-model="scope.row.code"
                ref="myCascaderOrg"
                @change="changeOrg(scope.row)"
              ></el-cascader>
            </div>
            <div v-else>
              <span>{{ scope.row.code }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="地区名称">
          <template slot-scope="scope">
            <div
              v-if="scope.row.editRowVisible"
            ><!--  v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id"-->
              <el-cascader
                :options="options"
                :props="areaprops"
                clearable
                filterable
                :show-all-levels="false"
                v-model="scope.row.area"
                ref="myCascader"
                @change="changeArea(scope.row)"
              ></el-cascader>
            </div>
            <div v-else>
              <span>{{ scope.row.area }}</span>
            </div>
          </template> 
        </el-table-column> 
        <el-table-column prop="price" label="合同价">
          <template slot-scope="scope">
            <div
              v-if="scope.row.editRowVisible" 
            ><!-- v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id" -->
              <el-input
                placeholder="请输入"
                v-model="scope.row.price"
                oninput="value=value.replace(/[^\d.]/g,'')"
              >
              </el-input>
            </div>
            <div v-else>
              <span>{{ scope.row.price }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              type="warning"
              @click="editSingleDiffPriceRule(scope.row)"
              v-show="!scope.row.editRowVisible"
            > 
              编辑
            </el-link>
            <el-link
              type="success"
              @click="saveSingleDiffPriceRule(scope.row)"
              v-show="scope.row.editRowVisible" 
            >
              保存
            </el-link>
            &nbsp;
            <!--   
            <el-link
              type="warning"
              v-show="!scope.row.editRowVisible"
              @click="copyColumn(scope.row)"
            >
              复制
            </el-link>
            &nbsp;-->
            <el-link type="danger" @click="disable(scope.row.index)">
              删除
            </el-link>
          </template> 
        </el-table-column>
      </el-table>

      <div class="addColumn">
        <el-button type="text" icon="el-icon-plus" @click="addColumnRule">
          增加差异规则
        </el-button>
      </div>
    </div>
 
  </div>
</template>

<script>
import regionData from '../../assets/js/regionChoose.js'
export default {
  props: { 
    // pricerule:{   //1：添加定价规则，2：编辑定价规则
    //   type:Number
    // },
    fixdata:{    //定价规则id:获取定价规则相关信息
      type: Object,
      default: function () {
        return {}
      }
    }, 
  },
 

  data() {
   
    return {
      selectData:{}, 
      
      priceRuleForm:{
        gift_name:'',
        gift_id:'',
        service_id:'',
        is_diff:false,
        clear_mode:null,
        valuation_type:null, 
        price:'',  //设置统一价的默认值：0
        start_time:'',
        end_time:'',
        remark:''
      },
      priceRuleFormRules: {
        //clear_mode: [{ required: true, message: '请选择结算类型', trigger: 'change' }],
        valuation_type: [{ required: true, message: '请选择计价类型', trigger: 'change' }],
        price: [{ required: true, message: '请输入统一价', trigger: 'change' }], 
        start_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ],
        end_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ]
      },
      nosettle_priceRuleFormRules: { 
        start_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ],
        end_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ]
      },

      // 差异价规则表
      diffTableData: [],
      addDiffPriceData: {
        code:'',
        area: '', 
        price: '', 
        editRowVisible: true
      },

      options: [],
      orgprops: {
        checkStrictly: true,
        children: 'children',
        value: 'code',
        label: 'name', 
      },
      areaprops: {
        checkStrictly: true,
        children: 'childs',
        value: 'code',
        label: 'name', 
      },
      hasClearmode:false,
      partner_id:'',
      
    }
  },
  watch: { 
    priceRuleForm:{
      handler(newValue, oldValue) {
        //  console.log('watch')
        // // console.log(oldValue) 
         console.log(newValue)
        // console.log(newValue.clear_mode) 
      },
      deep: true
    }  
  },
  
  created() {
    
    if(this.fixdata){
      
      this.priceRuleForm.gift_name=this.fixdata.gift_name
      this.priceRuleForm.service_id=this.fixdata.service_id
      this.priceRuleForm.clear_mode=this.fixdata.clear_mode.id
      this.hasClearmode=true

      // console.log(this.priceRuleForm.clear_mode)

      if(this.priceRuleForm.clear_mode==3){
        this.priceRuleForm.price=0
      }

      this.partner_id=this.fixdata.partner_id 
      this.getSelectData() 
    } 

    this.getOptions()   //获取城市：
 
  },
  updated(){
   
  },

  methods: {
    async getSelectData() {   //获取筛选条件数据：
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'get_service,clear_mode,valuation_type,org_tree',partner_id:this.partner_id  
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
 

    getOptions() {
      var arr = regionData
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].childs.length; j++) {
          delete arr[i].childs[j].childs
        }
      }
      this.options = arr
    },

    //校验数据：
    validateForm() {
      let flag = null
      this.$refs.priceRuleFormRef.validate(async (valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
        }
      })
      return flag
    },
     
    tableRowClassName({ row, rowIndex }) {    //   把每一行的索引放进row 
      row.index = rowIndex
    },

    changeOrg(row){   //选择机构名称
      //console.log("选择机构名称:"); console.log(this.$refs.myCascaderOrg.getCheckedNodes())
      row.orgName = this.$refs.myCascaderOrg.getCheckedNodes().label
    },
    changeArea(row) { 
      row.regionName = this.$refs.myCascader.getCheckedNodes().label
    },
    // copyColumn(row) {
    //   var newRow = Object.assign({}, row)
    //   newRow.id = ''
    //   newRow.editRowVisible = true
    //   console.log(newRow)
    //   this.diffTableData.splice(row.index + 1, 0, newRow) 
    // },
    disable(index) {    //删除差异价：在未提交前的单项删除
      this.diffTableData.splice(index, 1)
    },
    addColumnRule() { 
      this.diffTableData.push({
        id:'',
        code:'',
        area: '', 
        price: '',
        price_id: '', 
        editRowVisible: true
      })
    },
   
    saveSingleDiffPriceRule(row){    //添加差异价表格中的单项保存事件:
  
        if(row.code && row.area && row.price){ 
          row.editRowVisible = false 
        }else{
          this.$message.error('差异价参数缺失') 
        } 
        
    },
  
    
    editSingleDiffPriceRule(row) { 
      row.editRowVisible = true 
    },
 
    getFinalData() {
      if (this.priceRuleForm.is_diff && this.diffTableData.length === 0) {
         return this.$message.error('请配置差异价规则')
      }
      // console.log("获取差异价数据：")
      // console.log(this.diffTableData)
      var diff = []
      for (let i = 0; i < this.diffTableData.length; i++) {
        const item = {}
        item.area = this.diffTableData[i].area[this.diffTableData[i].area.length - 1]
        item.code = this.diffTableData[i].code[this.diffTableData[i].code.length - 1] 
        item.price = this.diffTableData[i].price
        diff.push(item)
      }
      this.priceRuleForm.diff_rule = diff 
      this.priceRuleForm.valuation_type = this.priceRuleForm.valuation_type 
     
      //this.priceRuleForm.remark = this.priceRuleForm.remark 

      this.$emit('showPriceRuleRef', this.priceRuleForm)
    },
   
    // 清空数据
    resetAllData() {
      // 清空校验  
      this.$refs.priceRuleFormRef.resetFields()
      this.diffTableData = []
      this.priceRuleForm={}
    },
  }
}
</script>
<style lang="less" scoped>
.addColumn {
  margin-top: -16px;
  text-align: center;
  border: 1px solid #eee;
  margin-bottom: 10px;
}
.line {
  text-align: center;
}
</style>
